package yw

import (
	"LogisticsPort/model"
	"LogisticsPort/sql"
	"errors"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func product(r *gin.RouterGroup) {
	product := r.Group("/product")
	{
		product.POST(sql.RequestAdd, productTypeAdd)
		product.POST(sql.RequestUpdate, productTypeUpdate)
		product.GET(sql.RequestDelete, productTypeDelete)
		product.GET(sql.RequestList, productTypeList)
		product.GET(sql.RequestData, productTypeData)
	}
}

// ================= 成品类型 =========================
func productTypeAdd(c *gin.Context) {
	sql.HttpAddTable(c, "yw_product", &model.FinishedProduct{}, nil)
}

func productTypeUpdate(c *gin.Context) {
	sql.HttpHandle(sql.ADD, c, func(db *gorm.DB) (*gorm.DB, interface{}) {
		var bean model.FinishedProduct
		if err := c.Bind(&bean); err != nil {
			db.Error = errors.New(sql.ErrorParams)
			return db, nil
		}
		if err := db.
			Where("id = ?", bean.ID).
			Table("yw_product").
			Updates(map[string]interface{}{
				"inventory_weight": gorm.Expr("inventory_weight + ?", bean.InventoryWeight),
				"inventory_number": gorm.Expr("inventory_number + ?", bean.InventoryNumber),
			}).Error; err != nil {
			db.Error = err
			return db, nil
		}
		return db, bean
	})
}

/*
DECLARE v_count INT;
SELECT COUNT(*) INTO v_count FROM yw_product_sales;
IF COUNT(*) > 0 THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = v_count;
END IF;
*/
func productTypeDelete(c *gin.Context) {
	sql.HttpDeleteTableById(c, "yw_product", &model.FinishedProduct{})
}

func productTypeList(c *gin.Context) {
	sql.HttpListTable(c, "yw_product", &[]model.FinishedProduct{}, nil)
}

func productTypeData(c *gin.Context) {
	sql.HttpDataTableById(c, "yw_product", &model.FinishedProduct{})
}
